#include "54func.h"
#include "serverFunc.h"


// token加密函数
int generateJwt(cmd_t* pcmd) {
    char* jwt;
    size_t jwt_length;
    struct l8w8jwt_encoding_params params;
    l8w8jwt_encoding_params_init(&params);

    params.alg = L8W8JWT_ALG_HS512;

    params.sub = "Netdisk";
    params.iss = "Niqiu";
    params.aud = "Daoyou";

    params.iat = 0;
    params.exp = 0x7fffffff;

    params.secret_key = (unsigned char*) pcmd->user;
    params.secret_key_length = strlen(pcmd->user);

    params.out = (char**) &jwt;
    params.out_length = &jwt_length;

    l8w8jwt_encode(&params);
    /* Always free the output jwt string! */
    strcpy(pcmd->token, jwt);
    // printf("%s\n", pcmd->token);
    //l8w8jwt_free(cmd->token);

    return 0;
}

// token解码函数
int verifyJwt(cmd_t* pcmd) {
    {
        struct l8w8jwt_decoding_params params;
        l8w8jwt_decoding_params_init(&params);

        params.alg = L8W8JWT_ALG_HS512;

        params.jwt = (char*)pcmd->token;
        params.jwt_length = strlen(pcmd->token);

        params.verification_key = (unsigned char*)pcmd->user;
        params.verification_key_length = strlen(pcmd->user);

        /* 
         * Not providing params.validate_iss_length makes it use strlen()
         * Only do this when using properly NUL-terminated C-strings! 
         */
        params.validate_iss = "Niqiu"; 
        params.validate_sub = "Netdisk";

        /* Expiration validation set to false here only because the above example token is already expired! */


        enum l8w8jwt_validation_result validation_result;

        int decode_result = l8w8jwt_decode(&params, &validation_result, NULL, NULL);

        if (decode_result == L8W8JWT_SUCCESS && validation_result == L8W8JWT_VALID) 
        {
            return 1;
        }
        else
        {
            return 0;
        }
    }
}

